package com.zt.english.utils

import android.content.Context
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import androidx.core.content.ContextCompat
import java.util.regex.Pattern

/**
 * 关键字体颜色改变  工具类
 */
object FindUtil {
    /*** 关键字高亮变色 ** @param color 变化的色值 * @param text 文字 * @param keyword 文字中的关键字 * @return */
    fun findSearch(
        context: Context?,
        color: Int,
        text: String?,
        keyword: String?
    ): SpannableString {
        val s = SpannableString(text)
        val p = Pattern.compile(keyword)
        val m = p.matcher(s)
        while (m.find()) {
            val start = m.start()
            val end = m.end()
            s.setSpan(
                ForegroundColorSpan(
                    ContextCompat.getColor(
                        context!!,
                        color
                    )
                ), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
            )
        }
        return s
    }

    /*** 多个关键字高亮变色 ** @param color 变化的色值 * @param text 文字 * @param keyword 文字中的关键字数组 * @return */
    fun findSearch(
        context: Context?,
        color: Int,
        text: String?,
        vararg keyword: String?
    ): SpannableString {
        val s = SpannableString(text)
        for (i in 0 until keyword.size) {
            val p = Pattern.compile(keyword[i])
            val m = p.matcher(s)
            while (m.find()) {
                val start = m.start()
                val end = m.end()
                s.setSpan(
                    ForegroundColorSpan(
                        ContextCompat.getColor(
                            context!!,
                            color
                        )
                    ), start, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        }
        return s
    }
}